<template>
  <div class="login-container">
    <div class="logo" />
    <div class="form">
      <h1>登录</h1>
      <el-card shadow="never" class="login-card">
        <!--登录表单-->
        <el-form v-if="currentLogin === 'phone'" ref="form" :model="loginForm" :rules="loginRules">
          <el-form-item prop="mobile">
            <el-input v-model="loginForm.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" show-password placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="isAgree">
            <el-checkbox v-model="loginForm.isAgree">
              用户平台使用协议
            </el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button style="width:350px" type="primary" @click="login">登录</el-button>
          </el-form-item>
        </el-form>
        <div v-else-if="currentLogin === 'qrcode'" class="qrcode-login">
          <div v-if="codeState === 4" class="qrcode_layer timeout">
            <span>点击刷新</span>
            <i class="el-icon-refresh-left" @click="createQrCode" />
          </div>
          <div v-if="codeState === 5" class="qrcode_layer timeout">
            <span>用户已取消</span>
            <i class="el-icon-refresh-left" @click="createQrCode" />
          </div>
          <div v-if="codeState === 2" class="qrcode_layer scan_success">
            <span>扫描成功</span>
            <i class="el-icon-check" />
          </div>
          <canvas ref="qrcodeCanvas" />
        </div>
        <div class="multi-login">
          <el-button size="mini" class="multi-button" @click="currentLogin='phone'">手机号登录</el-button>
          <el-button size="mini" class="multi-button" @click="currentLogin='qrcode'">二维码登录</el-button>
        </div>
        <div class="login-remind">
          仅用于IT培训教学使用，为保障您的个人信息安全，请勿向平台录入任何个人敏感信息 (如手机号、身份证号等)!
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getQrCodeKeyAPI, getQrCodeStateAPI } from '@/api/user'
import QrCode from 'qrcode'
export default {
  name: 'Login',
  data() {
    return {
      // 判断当前的登录模式phone / qrcode
      currentLogin: 'phone',
      qrCodeKey: '', // 加密串变量
      // timer: null, // 定时器变量，可以不用再data中声明，因为只有响应式数据才需要在data中声明，timer只是一个标记，没有在template中使用，所以不需要响应式，只需要能够从this中读取和设置就足够了
      loginForm: {
        mobile: '13800000002',
        password: 'hm#qd@23!',
        isAgree: true
      },
      loginRules: {
        mobile: [{
          required: true,
          message: '请输入手机号',
          trigger: 'blur'
        }, {
          pattern: /^(1[3-9]\d{9})|(12000000002)$/,
          message: '手机号格式不正确',
          trigger: 'blur'
        }],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }, {
          min: 6,
          max: 16,
          message: '密码长度应该为6-16位之间',
          trigger: 'blur'

        }],
        // required只能检测 null undefined ""
        isAgree: [{
          validator: (rule, value, callback) => {
            // rule校验规则
            // value 校验的值
            // callback 函数 - promise resolve reject
            // callback() callback(new Error(错误信息))
            value ? callback() : callback(new Error('您必须勾选用户的使用协议'))
          }
        }]
      }
    }
  },
  watch: {
    currentLogin(value) {
      if (value === 'qrcode') {
        this.createQrCode()
      } else {
        // 切换到手机号登录模式，轮询结束
        clearInterval(this.timer) // 只要不是扫码登录就停止
      }
    }
  },
  methods: {
    login() {
      this.$refs.form.validate(async(isOK) => {
        if (isOK) {
          await this.$store.dispatch('user/login', this.loginForm)
          // Vuex 中的action 返回的promise
          // 跳转主页
          this.$router.push('/')
        }
      })
    },
    // 获取加密串
    async getQrCodeKey() {
      this.qrCodeKey = await getQrCodeKeyAPI()
    },
    // 生成二维码
    async createQrCode() {
      this.codeState = 1 // 回到初始状态
      await this.getQrCodeKey()
      // 开启轮询
      this.beginLoopCheck()
      // 使用QrCode生成二维码
      // 注意点：需要使用$nextTick()，因为这个方法是在watch中监听的currentLogin的变化，此时更新还未完成，我们需要在下个事件循环中获取到dom
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.qrcodeCanvas, this.qrCodeKey, {
          width: 300, // 二维码宽高300
          height: 300
        })
      })
    },
    beginLoopCheck() {
      // 获取登录状态码，并进行轮询
      // 1-切换到手机号登录，轮询结束
      // 2-请求查询状态异常，轮询结束
      // 3-二维码超时，轮询结束
      // 4-页面卸载时，轮询结束
      // 5-用户扫码登录成功，轮询结束
      const checkState = async() => {
        try {
          const { codeState, token } = await getQrCodeStateAPI({ qrcode_key: this.qrCodeKey })
          this.codeState = codeState
          // 登录状态码为3（扫码登录成功）4（加密串失效）5（扫码后取消登录），轮询结束，但是3需要跳转页面
          if (this.codeState === 4 || this.codeState === 5) {
            clearInterval(this.timer)
          } else if (this.codeState === 3) {
            clearInterval(this.timer)
            // 登录设置token
            this.$store.commit('user/setToken', token)
            // 跳转到首页
            this.$router.push('/')
          }
        } catch (error) {
          console.log(error)
          // 登录异常，轮询结束
          clearInterval(this.timer)
        }
      }
      this.timer = setInterval(() => {
        checkState()
      }, 2000)
    },
    // 页面卸载时，清除定时器
    beforeDestroy() {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss">
.qrcode_layer {
    position: absolute;
    width: 150px;
    height: 150px;
    left: 50%;
    top: 50%;
    transform: translate(-75px, -75px);
    opacity: 0.9;
    background: #e1dede;
    display: flex;
    justify-content: center;
    align-items: center;
    i {
      font-size: 40px;
      padding: 10px;
    }
  }
  .scan_success {
    i {
      color: #67C23A;
    }
  }
  .timeout {
    i {
      color: #F56C6C;
    }
  }
.qrcode-login {
    width: 350px;
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
  }
.multi-login {
    margin: 10px 0;
    display: flex;
    width: 350px;
    .multi-button {
      flex: 1;
    }
  }
.login-container {
  display: flex;
  align-items: stretch;
  height: 100vh;
  .logo {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    justify-content: center;
    flex: 3;
    padding: 0 100px;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png)
      no-repeat center / cover;
    border-top-right-radius: 60px;
  }
  .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;
    .el-card {
      border: none;
      padding: 0;
    }
    h1 {
      padding-left: 20px;
      font-size: 24px;
    }
    .el-input {
      width: 350px;
      height: 44px;
      .el-input__inner {
        background: #f4f5fb;
      }
    }
    .el-checkbox {
      color:#606266;
    }
  }
  .login-remind {
    width: 350px;
    font-size: 14px;
    color: red;
  }
}
</style>
